package com.lfy.commons.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lfy.auth.domain.entity.UserEntity;
import com.lfy.common.constant.AuthConstant;
import com.lfy.common.constant.EnvConfigConstant;
import com.lfy.common.enums.BaseEnum;
import com.lfy.common.result.R;
import com.lfy.commons.anno.user.NoNeedLogin;
import com.lfy.commons.utils.CookieUtil;
import com.lfy.commons.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Configuration
@Slf4j
public class AuthHandlerInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<UserEntity> authLocal = ThreadLocal.withInitial(() -> null);
    public static final ThreadLocal<Boolean> isTimeOut = ThreadLocal.withInitial(() -> Boolean.FALSE);



    public static String url;
    public static final String STRING_RESOURCE_CLASS = "org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)";

    static {
        url = EnvConfigConstant.CORS_URL;
    }

    {
        log.info("The current domain name is {}", url);
    }

    public static void main(String[] args) {
        System.out.println(url);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        this.crossDomainConfig(response);
        isTimeOut.set(Boolean.FALSE);
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        boolean isNoNeedLogin = ((HandlerMethod) handler).getMethodAnnotation(NoNeedLogin.class) != null;
        if (isNoNeedLogin) {
            return true;
        }
        Cookie[] cookies = request.getCookies();
        String token = null;
        String fastToken = null;
        ObjectMapper objectMapper = new ObjectMapper();
        if(cookies == null || cookies.length == 0){
            NoLogin(response, objectMapper,BaseEnum.authEnum.NO_LOGIN);
            return false;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(AuthConstant.JWT_HEADER)) {
                token = cookie.getValue();

            }
            if(cookie.getName().equals(AuthConstant.JWT_FAST_HEADER)){
                fastToken = cookie.getValue();
            }
        }
        if(Objects.isNull(token) || Objects.isNull(fastToken)){
            NoLogin(response, objectMapper,BaseEnum.authEnum.NO_LOGIN);
            return false;
        }
        Claims fastClaims = JwtUtil.parseJwt(fastToken);
        if(!Objects.isNull(fastClaims) ){
            Object o = fastClaims.get("user");
            if(!Objects.isNull(o)){
                UserEntity userEntity = objectMapper.convertValue(o, UserEntity.class);
                authLocal.set(userEntity);
                return true;
            }
        }


        Claims claims = JwtUtil.parseJwt(token);
        if (Objects.isNull(claims)) {
            NoLogin(response, objectMapper,BaseEnum.authEnum.NO_LOGIN);
            return false;
        }
        Object user = claims.get("user");

        if (Objects.isNull(user)) {
            NoLogin(response, objectMapper,BaseEnum.authEnum.NO_TIME_LOGIN);
            return false;
        }

        UserEntity userEntity = objectMapper.convertValue(user, UserEntity.class);
        authLocal.set(userEntity);
        isTimeOut.set(Boolean.TRUE);
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(isTimeOut.get()){
            UserEntity userEntity = authLocal.get();
            String jwt = JwtUtil.createJwt(userEntity, 1000 * 60 * 60*6);
            String fastJwt = JwtUtil.createJwt(userEntity, 1000 * 60 * 60);
            CookieUtil.setCookie(null,response, AuthConstant.JWT_HEADER,jwt,1000 * 60 * 60*6);
            CookieUtil.setCookie(null,response, AuthConstant.JWT_FAST_HEADER,fastJwt,1000 * 60 * 60);
        }
        authLocal.remove();
        isTimeOut.remove();

    }

    private void NoLogin(HttpServletResponse response, ObjectMapper objectMapper,BaseEnum baseEnum) throws IOException {
        R<Object> error = R.error(baseEnum);
        response.setContentType("application/json;charset=utf-8");
        String errorMsg = objectMapper.writeValueAsString(error);
        response.getWriter().write(errorMsg);
    }

    /**
     * 配置跨域
     *
     * @param response
     */
    private void crossDomainConfig(HttpServletResponse response) {

        response.setHeader("Access-Control-Allow-Origin", url);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Expose-Headers", "*");
        response.setHeader("Access-Control-Allow-Headers", "Authentication,Origin, X-Requested-With, Content-Type, " + "Accept");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");

    }
}
